class Posts {
  final int? id;
  final String title;
  final String content;
  final String? createTime; // 显示时使用；后端为 createdTime
  final int? userId;
  final String userName; // 对应后端 author
  final String? imageUrl; // 兼容老字段（封面）
  final List<String> imageUrls; // 多图，后端为逗号分隔字符串 imageUrls
  final String? avatarUrl;
  final int? likes;
  final bool isLiked; // 当前用户是否已点赞

  Posts({
    this.id,
    String? title,
    String? content,
    this.createTime,
    this.userId,
    String? userName,
    this.imageUrl,
    List<String>? imageUrls,
    this.avatarUrl,
    this.likes,
    bool? isLiked,
  })  : title = title ?? '',
        content = content ?? '',
        userName = userName ?? '',
        imageUrls = imageUrls ?? const [],
        isLiked = isLiked ?? false;

  factory Posts.fromJson(Map<String, dynamic> json) {
    return Posts(
      id: _asInt(json['id']),
      title: _asString(json['title'], ''),
      content: _asString(json['content'], ''),
      createTime: _asString(json['createTime'] ?? json['createdTime']),
      userId: _asInt(json['userId']),
      userName: _asString(json['author'] ?? json['userName'], ''),
      imageUrl: _asString(json['imageUrl'] ?? json['imagePath']),
      imageUrls: _parseImageUrls(json['imageUrls'] ?? json['images']),
      avatarUrl: _asString(json['avatarUrl']),
      likes: _asInt(json['likes']),
      isLiked: json['isLiked'] == true || json['liked'] == true,
    );
  }

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
      if (id != null) 'id': id,
      'title': title,
      'content': content,
      if (createTime != null) 'createdTime': createTime,
      if (userId != null) 'userId': userId,
      'author': userName,
      if (imageUrl != null && imageUrl!.isNotEmpty) 'imageUrl': imageUrl,
      if (imageUrls.isNotEmpty) 'imageUrls': imageUrls.join(','),
      if (avatarUrl != null && avatarUrl!.isNotEmpty) 'avatarUrl': avatarUrl,
      if (likes != null) 'likes': likes,
      'isLiked': isLiked,
    };
  }
}

int? _asInt(Object? v) {
  if (v == null) return null;
  if (v is int) return v;
  if (v is String) return int.tryParse(v);
  return null;
}

String? _asString(Object? v, [String? defaultValue]) {
  if (v == null) return defaultValue;
  return v.toString();
}

List<String> _asStringList(Object? v) {
  if (v == null) return const [];
  if (v is List) {
    return v.map((e) => e?.toString() ?? '').where((e) => e.isNotEmpty).toList();
  }
  return const [];
}

List<String> _parseImageUrls(Object? v) {
  if (v == null) return const [];
  if (v is List) return _asStringList(v);
  final s = _asString(v, '') ?? '';
  if (s.isEmpty) return const [];
  return s.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
}


